package gizwits.phnix;

/**
 * 测试芬尼克兹
 * Created by Robo on 2017/12/6.
 */
public class ProtocolTest {

   /* public static void main(String[] args) {
        String source = "631003e9005ab457463136313230333030333600000000010103e90000000200dc00000001fffe0000000100010014001e00550050001400c000010050002d00960000009600320041015e01ae00410096ff9c005a015e01ae005000c800000014ff88003c00030190009600960046006400140064003700c80061012c006e0000006402ee003202ee0032025800000006003201f40000000000320258000000010000000000000002001e00030001000000000000000000000000";
        char[] chars = source.toCharArray();
        byte[] bytes = new byte[chars.length / 2];
        for (int i = 0; i < chars.length; i += 2) {
            int result = 0;
            for (int ii = 0; ii < 2; ii++) {
                int digit = Character.digit(chars[i + ii], 16);
                result *= 16;
                result -= digit;
            }
            bytes[i / 2] = (byte) (-result);
        }
        int ret = getCrc16(bytes);
        System.out.println(String.format("%x", ret));
    }*/

    public static void main(String[] args) {
        String source = "631007d1005ab457463136313230333030333600000000010107d100000001000000000000000000000000000000fa000000000082000000000000000000000000000000000000000000340000000000000000000000000000000000000000000cfffe00130021001d000c000000000000004600005aa500000000000000000000002800d5000000af00000000000000000000000000000000020000000000000000000000000000000000000d0239000000000000000000000000";
        byte[] by = new byte[source.length() / 2];
        for (int i = 0; i < source.length(); i +=2) {
            String bb = source.substring(i, i + 2);
            by[i / 2] = Integer.valueOf(bb, 16).byteValue();
        }
        int ret = getCrc16(by);
        System.out.println(String.format("%x", ret));
    }

    public static int getCrc16(byte[] arr_buff) {
        int len = arr_buff.length;

        //预置 1 个 16 位的寄存器为十六进制FFFF, 称此寄存器为 CRC寄存器。
        int crc = 0xFFFF;
        int i, j;
        for (i = 0; i < len; i++) {
            //把第一个 8 位二进制数据 与 16 位的 CRC寄存器的低 8 位相异或, 把结果放于 CRC寄存器
            crc = ((crc & 0xFF00) | (crc & 0x00FF) ^ (arr_buff[i] & 0xFF));
            for (j = 0; j < 8; j++) {
                //把 CRC 寄存器的内容右移一位( 朝低位)用 0 填补最高位, 并检查右移后的移出位
                if ((crc & 0x0001) > 0) {
                    //如果移出位为 1, CRC寄存器与多项式A001进行异或
                    crc = crc >> 1;
                    crc = crc ^ 0xA001;
                } else
                    //如果移出位为 0,再次右移一位
                    crc = crc >> 1;
            }
        }
        return crc;
    }
}
